package com.example.mall.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mall.client.SearchFeignClient;
import com.example.mall.constants.BaseConstants;
import com.example.mall.doc.ProductsDoc;
import com.example.mall.domain.Categories;
import com.example.mall.domain.ProductImages;
import com.example.mall.domain.Products;
import com.example.mall.dto.ProductsDto;
import com.example.mall.exception.ErrorEnumCode;
import com.example.mall.exception.GlobalCustomerException;
import com.example.mall.mapper.CategoriesMapper;
import com.example.mall.mapper.ProductInventoryMapper;
import com.example.mall.mapper.ProductSpecsMapper;
import com.example.mall.mapper.ProductsMapper;
import com.example.mall.mq.ProductMessageSender;
import com.example.mall.query.PageDTO;
import com.example.mall.query.ProductsQuery;
import com.example.mall.result.JSONResult;
import com.example.mall.service.IProductImagesService;
import com.example.mall.service.IProductsService;
import com.example.mall.util.AssertUtil;
import com.example.mall.util.CodeGenerateUtils;
import com.example.mall.util.CopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商品基本信息表 服务实现类
 * </p>
 *
 * @author whale
 * @since 2025-05-06
 */
@Service
@Slf4j
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products> implements IProductsService {

    @Autowired
    private ProductsMapper productsMapper;
    @Autowired
    private IProductImagesService productImagesService;
    @Autowired
    private ProductInventoryMapper productInventoryMapper;
    @Autowired
    private ProductSpecsMapper productSpecsMapper;
    @Autowired
    private CategoriesMapper categoriesMapper;
    @Autowired
    private SearchFeignClient searchFeignClient;
    @Autowired
    private ProductMessageSender productMessageSender;

    /*
     * Description：商品上架
     * 1.判断参数
     * 2.判断商品状态必须是下线状态
     * 3.修改商品状态为：上线状态
     * 4.调用Feign保存商品到ES中
     * 5.消息推送
     */
    @Override
    public void onLineProduct(Long id) {
//* 1.判断参数
        AssertUtil.isNotNull(id,"无效的参数，刷新重试" );

        //* 2.判断课程状态必须是下线状态
        Products products = productsMapper.selectById(id);
        AssertUtil.isNotNull(products,"无效的商品，请重试" );
        AssertUtil.isTrue(products.getIsActive() == BaseConstants.ProductConstants.STATUS_OFF_LIINE,
                "商品状态异常");

        //* 3.修改课程状态为：上线状态
        products.setIsActive(BaseConstants.ProductConstants.STATUS_ON_LIINE);
        Date date = new Date();
        products.setCreateDate(date);


        //* 4.调用Feign保存课程到ES中
        Categories categories = categoriesMapper.selectById(products.getCategoryId());
        AssertUtil.isNotNull(categories,"无效的商品分类，请重试");

        List<ProductImages> productImages = productImagesService.selectByProductId(products.getProductId());
        AssertUtil.isNotNull(productImages,"无效的商品图片，请重试");

        ProductsDoc doc = new ProductsDoc();
        doc.setProductId(products.getProductId());
        doc.setCategoryId(categories.getCategoryId());
        doc.setName(products.getName());
        doc.setDescription(products.getDescription());
        doc.setPrice(products.getPrice());
        doc.setDiscountPrice(products.getDiscountPrice());
        doc.setStock(products.getStock());
        doc.setOnLineDate(new Date());
        doc.setUpdateDate(new Date());
        doc.setSaleCount(0);
        doc.setViewCount(0);
        doc.setCommentCount(0);

        productImages.stream().forEach(item->{
            if(StringUtils.equals(String.valueOf(BaseConstants.ProductConstants.STATUS_ON_LIINE),item.getIsMain())){
                doc.setPic(item.getImageUrl());
            }
        });

        JSONResult jsonResult = searchFeignClient.addProduct(doc);
        AssertUtil.isTrue(jsonResult.isSuccess(), "商品添加到ES失败");

        super.updateById(products);

        //推送消息
        try{
            productMessageSender.publishMessage(products);
        }catch (Exception e){
            e.printStackTrace();
            log.info("消息推送失败");
            throw new GlobalCustomerException(ErrorEnumCode.MESSAGE_PUSH_FAILED);
        }
    }

    /*
     * Description：商品下架
     * 1.判断参数
     * 2.判断商品状态必须是上线状态
     * 3.修改商品状态为：下线状态
     * 4.调用Feign删除商品到ES中
     * 5.消息推送
     */
    @Override
    public void offLineProduct(Long id) {

    }

    /*
     * Description：商品详情
     * 1.判断参数
     * 2.调用Feign查询商品详情
     * 3.返回商品详情
     */
    @Override
    public Object selectProductInfoById(Long id) {
        return null;
    }

    /*
     * Description：商品详情列表
     * 1.判断参数
     * 2.调用Feign查询商品详情列表
     * 3.返回商品详情列表
     */
    @Override
    public Object selectProductInfosById(List<Long> courseIds) {
        return null;
    }

    @Override
    public PageDTO<ProductsDto> queryPage(ProductsQuery productsQuery) {
        if (productsQuery == null) {
            productsQuery = new ProductsQuery();
        }
        Page<Products> page = productsQuery.toMpPageByDefaultCreateTimeAsc();
        Page<Products> cartPage = lambdaQuery()
                .like(productsQuery.getProductId()!= null, Products::getProductId, productsQuery.getProductId())
                .like(productsQuery.getCategoryId()!= null, Products::getCategoryId, productsQuery.getCategoryId())
                .like(productsQuery.getName()!= null, Products::getName, productsQuery.getName())
                .like(productsQuery.getDescription()!= null, Products::getDescription, productsQuery.getDescription())
                .like(productsQuery.getPrice()!= null, Products::getPrice, productsQuery.getPrice())
                .like(productsQuery.getDiscountPrice()!= null, Products::getDiscountPrice, productsQuery.getDiscountPrice())
                .like(productsQuery.getStock()!= null, Products::getStock, productsQuery.getStock())
                .like(productsQuery.getIsActive()!= null, Products::getIsActive, productsQuery.getIsActive())
                .orderByDesc(Products::getUpdateDate)
                .page(page);
        return PageDTO.of(cartPage, ProductsDto.class);
    }

    @Override
    public Products queryProductsById(Long id) {
        AssertUtil.isNotNull(id,"无效的参数，刷新重试" );
        return productsMapper.selectById(id);
    }

    @Override
    public List<Products> queryProductsList() {
        return this.list();
    }

    @Override
    public void insert(ProductsDto productsDto) {
        Products products = new Products();
        CopyUtils.copyProperties(productsDto, products);
        products.setProductId(CodeGenerateUtils.generateUniqueId());
        products.setCreateDate(new Date());
        products.setUpdateDate(new Date());
        products.setIsActive(BaseConstants.LOSE_STATUS);
        productsMapper.insert(products);
    }

    @Override
    public void update(ProductsDto productsDto) {
        AssertUtil.isNotNull(productsDto.getProductId(),"无效的参数，刷新重试" );
        Products products = productsMapper.selectById(productsDto.getProductId());
        AssertUtil.isNotNull(products,"无效的商品，请重试" );
        CopyUtils.copyProperties(productsDto, products);
        products.setUpdateDate(new Date());
        productsMapper.updateById(products);
    }

    @Override
    public void delete(Long id) {
        AssertUtil.isNotNull(id,"无效的参数，刷新重试" );
        Products products = productsMapper.selectById(id);
        AssertUtil.isNotNull(products,"无效的商品，请重试" );
        productsMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        AssertUtil.isNotNull(ids,"无效的参数，刷新重试" );
        List<Products> products = productsMapper.selectBatchIds(ids);
        AssertUtil.isNotNull(products,"无效的商品，请重试" );
        productsMapper.deleteBatchIds(ids);
    }
}
